import Fastify from "fastify";
import { fastifyTRPCPlugin } from "@trpc/server/adapters/fastify";
import { appRouter, type AppRouter } from "./router.js";
import swagger from "@fastify/swagger";
import swaggerUI from "@fastify/swagger-ui";
import cors from "@fastify/cors";

const server = Fastify({
  maxParamLength: 5000,
});

// 注册 CORS 插件（必须在其他插件之前注册）
server.register(cors, {
  origin: ["http://localhost:5173", "http://localhost:3000"],
  credentials: true,
});

// 注册 Swagger 文档
server.register(swagger, {
  openapi: {
    info: {
      title: "Fullstack tRPC API",
      description: "使用 tRPC + Fastify + Zod 构建的类型安全 API",
      version: "1.0.0",
    },
    servers: [
      {
        url: "http://localhost:3000",
        description: "开发服务器",
      },
    ],
  },
});

server.register(swaggerUI, {
  routePrefix: "/docs",
  uiConfig: {
    docExpansion: "list",
    deepLinking: false,
  },
  staticCSP: true,
  transformStaticCSP: (header) => header,
});

// 注册 tRPC 插件
server.register(fastifyTRPCPlugin, {
  prefix: "/trpc",
  trpcOptions: { router: appRouter },
});

// 健康检查端点
server.get("/health", async () => {
  return { status: "ok", timestamp: new Date().toISOString() };
});

// 启动服务器
const start = async () => {
  try {
    const port = 3000;
    const host = "0.0.0.0";
    
    await server.listen({ port, host });
    console.log(`🚀 服务器已启动`);
    console.log(`📍 本地访问: http://localhost:${port}`);
    console.log(`📚 API 文档: http://localhost:${port}/docs`);
    console.log(`🔌 tRPC 端点: http://localhost:${port}/trpc`);
  } catch (err) {
    server.log.error(err);
    process.exit(1);
  }
};

start();

